package estore.service;

import estore.model.Product;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ProductService {
    private List<Product> products = new ArrayList<>();
    private String dataFilePath;

    public ProductService() {
        loadConfig();
        loadData();
    }

    private void loadConfig() {
        Properties props = new Properties();
        try (InputStream is = new FileInputStream("config.properties")) {
            props.load(new InputStreamReader(is, "UTF-8"));
            dataFilePath = props.getProperty("data.file.path", "products.dat");
        } catch (IOException e) {
            System.err.println("配置文件加载失败，使用默认路径：" + e.getMessage());
            dataFilePath = "products.dat";
        }
    }

    private void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) return;

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            products = (List<Product>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("数据加载失败：" + e.getMessage());
        }
    }

    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(products);
            System.out.println("商品数据已保存到 " + dataFilePath);
        } catch (IOException e) {
            System.err.println("数据保存失败：" + e.getMessage());
        }
    }

    public List<Product> getAllProducts() {
        return products;
    }

    public Product getProductById(String id) {
        for (Product p : products) {
            if (p.getId().equals(id)) {
                return p;
            }
        }
        return null;
    }

    public void initTestData() {
        products.add(new Product("P001", "笔记本电脑", 5999.99, 10));
        products.add(new Product("P002", "机械键盘", 299.50, 30));
        products.add(new Product("P003", "无线鼠标", 129.00, 50));
    }

    public String getDataFilePath() {
        return dataFilePath;
    }
}